/*
 * Amendment History:
 * 
 * Date       By         Description 
 * ----------------------------------------------- 
 * Mar 24, 2010 Anselm Hou    Create the class
 */
package ctn.util;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.InputStream;

import javax.servlet.http.HttpServletResponse;
public class DownloadHelper
{
	
	private static int BUFFER_SIZE = 1024;

   /**
    * Construct for DownloadHelper
    */
   private DownloadHelper()
   {
      super();
   }
   
   public static void prepareDownload(HttpServletResponse response,MimeContentType contentType,String fileName,InputStream fileIS)
   throws Exception
   {
      prepareDownload(response,contentType,fileName,fileIS,true);
   }
   
   public static void prepareDownload(HttpServletResponse response,MimeContentType contentType,String fileName,InputStream fileIS,boolean isInline)
   throws Exception
   {
	   LogUtil.printDebug("BUFFER_SIZE=" + BUFFER_SIZE);
      prepareDownloadHeaders(response,contentType,fileName,isInline);
      BufferedOutputStream os=null;
      BufferedInputStream is=null;
      try
      {
         os=new BufferedOutputStream(response.getOutputStream());
         is=new BufferedInputStream(fileIS);
         
         byte[] byteA = new byte[BUFFER_SIZE];
         int read=0;
         while(read!=-1){
//            byteA=new byte[1024];
            read=is.read(byteA);
            if(read!=-1){
               os.write(byteA,0,read);
            }
         }
         os.flush();
      }
      finally
      {
         if(is!=null){
            is.close();
         }
         if(os!=null){
            try
            {
               os.close();
            }
            catch (Exception ex)
            {
            }
         }
      }
  
   }
   
   public static void prepareDownloadHeaders(HttpServletResponse response,MimeContentType contentType,String fileName,boolean isInline)
   throws Exception
   {

      response.setContentType(contentType.getContentType());
      response.setHeader("Pragma", "public");
      response.setHeader("Cache-Control", "max-age=0");
      if(isInline){
         response.setHeader("Content-Disposition", "inline;filename=" + new String(fileName.getBytes(), "UTF-8"));
      }
      else{
         response.setHeader("Content-Disposition", "attachment;filename=" +java.net.URLEncoder.encode(fileName, "UTF-8"));  

      }

   }
}
